<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Sage 2016/4/22  9:27
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Common\Model\BookModel;
use Admin\Common\Page;
use Think\Model;

Class StockController extends BaseController{

    function index(){
        $map['is_del'] = 0;
        $keywords = I('get.keywords');
        if (!empty($keywords)) {
            $map_or['book_id'] = $keywords;
            $map_or['tm'] = $keywords;
            $map_or['spbs'] = $keywords;
            $map_or['sm'] = ['like' , "%{$keywords}%"];
            $map_or['_logic'] = 'OR';
            $map['_complex'] = $map_or;
        }
        $m = D('Book');
        $count = $m->where($map)->count();// 查询满足要求的总记录数
        $Page = new  Page($count , C('page.size'));// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $where['keywords'] = $keywords;
        foreach ($where as $key => $val) {
//            $Page->parameter[ $key ] = urlencode($val);
            $Page->parameter[ $key ] = $val;
        }
        $show = $Page->show();// 分页显示输出
        $this->assign('page' , $show);// 赋值分页输出
        $data = $m->where($map)->relation(TRUE)->order('book_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->data = $data;
        $this->display();
    }

    function edit(){
        $book_id=I("get.book_id");
        $Book=M("book");
        $data=$Book->where(["book_id"=>$book_id])->find();
        $this->assign("data",$data);
        $this->display();
    }

    function doEdit(){
        $book_id=I("get.book_id");
        $data['stock_rent']=I("post.stock_rent");
        $data['stock_buy']=I("post.stock_buy");
        $Book=M("book");
        $Book->startTrans();
        $b=$Book->where(["book_id"=>$book_id])->field('book_id,tm ,spbs,sm,zyz,dj,stock_rent,stock_buy')->find();
        $d=$Book->where(["book_id"=>$book_id])->data($data)->save();
        if(!$d){
            $Book->rollback();
            $this->error("修改失败");
        }
        $content='库存调整,操作图书id:'.$b['book_id'].',原借阅库存:'.$b['stock_rent'].',调整为:'.$data['stock_rent'].',原购买库存:'.$b['stock_buy'].',调整为:'.$data['stock_buy'].',原图书信息为:';
        foreach($b as $k=>$v){
            $content.=$k.':'.$v.';';
        }
        $log=[
            'user_id'=>session('admin_user.user_id'),
            'content'=>$content
        ];
        $log_id=M('admin_stocklog')->data($log)->add();
        if($log_id){
            $Book->commit();
            $this->success("修改成功",U("index"));
        }else{
            $Book->rollback();
            $this->error("修改失败");
        }
    }
    //excel导入库存-增加
    public function import_add() {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = ['xls' , 'xlsx'];// 设置附件上传类型
        $upload->rootPath = './uploads/excel/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        $upload->autoSub = FALSE;
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功
            $Book=M('book');
            $Book->startTrans();
            $data = excel_import($upload->rootPath . $info["excel"]["savename"] , $info["excel"]['ext']);
            //第一行为字段
            $colname = $data[0];
            foreach($colname as $k=>$v){
                $colname[$k]=strtolower($v);
            }
            unset($data[0]);
            foreach ($data as $k => $v) {
                $save = NULL;
                $map=NULL;
                //获取book_id,库存字段更新
                if (!empty($v[0]) && in_array('spbs' , $colname)) {
                    //获取库存字段
                    $save=[];
                    foreach ($colname as $key => $value) {
                        switch($value){
                            case "spbs":$map[$value]=(string)$v[ $key ];break;
                            case "stock_rent":
                            case "stock_buy":$save[ $value ] = (string)$v[ $key ];break;
                            default:break;
                        }
                    }
                    $b=M('book')->where($map)->field('book_id,tm ,spbs,sm,zyz,dj,stock_rent,stock_buy')->find();
                    if($save == []){
                        continue;
                    }
                    unset($save['book_id']);
//                    if($save['stock_rent']<0 || $save['stock_buy']<0){
//                        $Book->rollback();
//                        $this->error("存在库存为负数的数据导入,无法导入,请检查");
//                    }
                    $Book->where($map)->setInc('stock_rent',$save['stock_rent']);
                    $Book->where($map)->setInc('stock_buy',$save['stock_buy']);

                    $content='批量库存导入,操作图书id:'.$b['book_id'].',原借阅库存:'.$b['stock_rent'].',增加库存:'.$save['stock_rent'].',原购买库存:'.$b['stock_buy'].',增加库存:'.$save['stock_buy'].',原图书信息为:';
                    foreach($b as $kk=>$vv){
                        $content.=$kk.':'.$vv.';';
                    }
                    $log=[
                        'user_id'=>session('admin_user.user_id'),
                        'content'=>$content
                    ];
                    $log_id=M('admin_stocklog')->data($log)->add();
                    if(!$log_id){
                        $Book->rollback();
                        $this->error("修改失败");
                    }
                } else {
                    //不存在则不进行操作
                    continue;
                }
            }
            $Book->commit();
        }
        $this->success('操作成功');
    }
    //excel导入库存-覆盖
    public function import_write() {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = ['xls' , 'xlsx'];// 设置附件上传类型
        $upload->rootPath = './uploads/excel/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        $upload->autoSub = FALSE;
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功
            $Book=M('book');
            $Book->startTrans();
            $data = excel_import($upload->rootPath . $info["excel"]["savename"] , $info["excel"]['ext']);
            //第一行为字段
            $colname = $data[0];
            foreach($colname as $k=>$v){
                $colname[$k]=strtolower($v);
            }
            unset($data[0]);
            foreach ($data as $k => $v) {
                $save = NULL;
                $map=NULL;
                //获取book_id,库存字段更新
                if (!empty($v[0]) && in_array('spbs' , $colname)) {
                    //获取库存字段
                    $save=[];
                    foreach ($colname as $key => $value) {
                        switch($value){
                            case "spbs":$map[$value]=(string)$v[ $key ];break;
                            case "stock_rent":
                            case "stock_buy":$save[ $value ] = (string)$v[ $key ];break;
                            default:break;
                        }
                    }
                    $b=M('book')->where($map)->field('book_id,tm ,spbs,sm,zyz,dj,stock_rent,stock_buy')->find();
                    if($save == []){
                        continue;
                    }
                    unset($save['book_id']);
                    $Book->where($map)->save($save);

                    $content='批量库存导入,操作图书id:'.$b['book_id'].',原借阅库存:'.$b['stock_rent'].',调整为:'.$save['stock_rent'].',原购买库存:'.$b['stock_buy'].',调整为:'.$save['stock_buy'].',原图书信息为:';
                    foreach($b as $kk=>$vv){
                        $content.=$kk.':'.$vv.';';
                    }
                    $log=[
                        'user_id'=>session('admin_user.user_id'),
                        'content'=>$content
                    ];
                    $log_id=M('admin_stocklog')->data($log)->add();
                    if(!$log_id){
                        $Book->rollback();
                        $this->error("修改失败");
                    }
                } else {
                    //不存在则不进行操作
                    continue;
                }
            }
            $Book->commit();
        }
        $this->success('操作成功');
    }
    //转入单导入
    function import_in(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = ['xls' , 'xlsx'];// 设置附件上传类型
        $upload->rootPath = './uploads/excel/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        $upload->autoSub = FALSE;
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功
            $Book=M('Book');
            $In=M('Book_in');
            $In->startTrans();
            $data = excel_import($upload->rootPath . $info["excel"]["savename"] , $info["excel"]['ext']);
            //第一行为字段
            $colname = $data[0];
            foreach($colname as $k=>$v){
                $colname[$k]=strtolower($v);
            }
            unset($data[0]);
            $exit_in_id=[];//重复单号检查
            foreach ($data as $k => $v) {
                $save = NULL;
                $map=NULL;
                //获取book_id,库存字段更新
                if (!empty($v[0]) && in_array('spbs' , $colname)) {
                    //获取库存字段
                    $add_in=[];
                    foreach ($colname as $key => $value) {
                        switch($value){
                            case "spbs":$map[$value]=(string)$v[ $key ];$add_book[ $value ] = (string)$v[ $key ];break;
                            case "in_id":
                            case "in_num":
                            case "in_time":$add_in[ $value ] = (string)$v[ $key ];break;
                            case "sm":
                            case "tm":
                            case "isbn":
                            case "zyz":
                            case "dj":
                            case "cbrq":
                            case "ysny":
                            case "jlrq":
                            case "yxxl":
                            case "yc":
                            case "bc":
                            case "kb":
                            case "press":$add_book[ $value ] = (string)$v[ $key ];break;
                            default:break;
                        }
                    }
                    if($add_in == []){
                        continue;
                    }
                    if(array_key_exists($add_in[ 'in_id' ],$exit_in_id) && $exit_in_id[$add_in[ 'in_id' ]]==true){
                        //存在即已通过检查,不做处理
                    }else{
                        //不存在即首次检查
                        $in=$In->where(['in_id'=>$add_in[ 'in_id' ]])->find();
                        if($in){
                            //已有则报错
                            $In->rollback();
//                            var_dump($in);
//                            var_dump($exit_in_id);
//                            var_dump(array_key_exists($add_in[ 'in_id' ],$exit_in_id));
//                            exit();
                            $this->error('此单已导入过,请勿重复导入,转入单号:'.$add_in['in_id']);
                        }else{
                            //没有则检查通过,并添加通过标识
                            $exit_in_id[$add_in[ 'in_id' ]]=true;
//                            echo $add_in[ 'in_id' ];
                        }
                    }
                    $b=$Book->where($map)->field('book_id,stock_rent,sm,tm,spbs,isbn')->find();
                    if(!$b){
                        //图书不存在,创建
                        $book_id=$Book->data($add_book)->add();
                        if($book_id){
                            $add_in[ 'book_id' ] = $book_id;
                            $b=$Book->where($map)->field('book_id,stock_rent,sm,tm,spbs,isbn')->find();
                        }else{
                            $In->rollback();
                            $this->error('创建图书编目错误,请检查格式');
                        }
                    }else{
                        $add_in[ 'book_id' ] = $b['book_id'];
                    }
                    //新增转入单数据
                    $ri=$In->data($add_in)->add();
                    if(!$ri){
                        $In->rollback();
                        $this->error('新增转入单出错,请检查格式');
                    }
                    //更新图书借阅数量
                    $rb=$Book->where($map)->setInc('stock_rent',$add_in['in_num']);
                    if(!$rb){
                        $In->rollback();
                        $this->error('更新图书库存出错,请检查格式');
                    }
                    $content='批量导入转入单,转入单号:'.$add_in['in_id'].'操作图书id:'.$b['book_id'].',原库存:'.$b['stock_rent'].',增加库存:'.$add_in['in_num'].',原图书信息为:';
                    foreach($b as $kk=>$vv){
                        $content.=$kk.':'.$vv.';';
                    }
                    $log=[
                        'user_id'=>session('admin_user.user_id'),
                        'content'=>$content
                    ];
                    $log_id=M('admin_stocklog')->data($log)->add();
                    if(!$log_id){
                        $Book->rollback();
                        $this->error("修改失败");
                    }
                } else {
                    //不存在则不进行操作
                    continue;
                }
            }
            $In->commit();
        }
        $this->success('操作成功');
    }
    //转出单导入
    function import_out(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = ['xls' , 'xlsx'];// 设置附件上传类型
        $upload->rootPath = './uploads/excel/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        $upload->autoSub = FALSE;
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功
            $Book=M('Book');
            $Out=M('Book_out');
            $Out->startTrans();
            $data = excel_import($upload->rootPath . $info["excel"]["savename"] , $info["excel"]['ext']);
            //第一行为字段
            $colname = $data[0];
            foreach($colname as $k=>$v){
                $colname[$k]=strtolower($v);
            }
            unset($data[0]);
            $exit_out_id=[];//重复单号检查
            foreach ($data as $k => $v) {
                $save = NULL;
                $map=NULL;
                //获取book_id,库存字段更新
                if (!empty($v[0]) && in_array('spbs' , $colname)) {
                    //获取库存字段
                    $add_out=[];
                    foreach ($colname as $key => $value) {
                        switch($value){
                            case "spbs":$map[$value]=(string)$v[ $key ];$add_book[ $value ] = (string)$v[ $key ];break;
                            case "out_id":
                            case "out_num":
                            case "out_time":$add_out[ $value ] = (string)$v[ $key ];break;
                            case "sm":
                            case "tm":
                            case "isbn":
                            case "zyz":
                            case "dj":
                            case "cbrq":
                            case "ysny":
                            case "jlrq":
                            case "yxxl":
                            case "yc":
                            case "bc":
                            case "kb":
                            case "press":$add_book[ $value ] = (string)$v[ $key ];break;
                            default:break;
                        }
                    }
                    if($add_out == []){
                        continue;
                    }
                    if(array_key_exists($add_out[ 'out_id' ],$exit_out_id) && $exit_out_id[$add_out[ 'out_id' ]]==true){
                        //存在即已通过检查,不做处理
                    }else{
                        //不存在即首次检查
                        $out=$Out->where(['out_id'=>$add_out[ 'out_id' ]])->find();
                        if($out){
                            //已有则报错
                            $Out->rollback();
                            $this->error('此单已导入过,请无重复导入,转入单号:'.$add_out['out_id']);
                        }else{
                            //没有则检查通过,并添加通过标识
                            $exit_out_id[$add_out[ 'out_id' ]]=true;
                        }
                    }
                    $b=$Book->where($map)->field('book_id,stock_rent,stock_buy,sm,tm,spbs,isbn')->find();
                    if(!$b){
                        //图书不存在,创建
                        $book_id=$Book->data($add_book)->add();
                        if($book_id){
                            $add_out[ 'book_id' ] = $book_id;
                            $b=$Book->where($map)->field('book_id,stock_rent,stock_buy,sm,tm,spbs,isbn')->find();
                        }else{
                            $Out->rollback();
                            $this->error('创建图书编目错误,请检查格式');
                        }
                    }else{
                        $add_out[ 'book_id' ] = $b['book_id'];
                    }
                    if($b['stock_rent']<$add_out[ 'out_num' ]){
                        $Out->rollback();
                        $this->error('库存扣除错误,请确认是否存在库存不足扣图书,对应单号:'.$add_out['out_id'].',对应图书spbs:'.$map['spbs']);
                    }
                    //新增转出单数据
                    $ro=$Out->data($add_out)->add();
                    if(!$ro){
                        $Out->rollback();
                        $this->error('新增转出单出错,请检查格式');
                    }
                    //更新图书借阅数量
                    $rb=$Book->where($map)->setDec('stock_rent',$add_out['out_num']);
                    if(!$rb){
                        $Out->rollback();
                        $this->error('更新图书库存出错,请检查格式');
                    }
                    $content='批量导入转出单,转出单号:'.$add_out['out_id'].'操作图书id:'.$b['book_id'].',原库存:'.$b['stock_rent'].',扣除库存:'.$add_out['out_num'].',原图书信息为:';
                    foreach($b as $kk=>$vv){
                        $content.=$kk.':'.$vv.';';
                    }
                    $log=[
                        'user_id'=>session('admin_user.user_id'),
                        'content'=>$content
                    ];
                    $log_id=M('admin_stocklog')->data($log)->add();
                    if(!$log_id){
                        $Book->rollback();
                        $this->error("日志记录失败失败");
                    }
                } else {
                    //不存在则不进行操作
                    continue;
                }
            }
            $Out->commit();
        }
        $this->success('操作成功');
    }
    //导出在借数-盘存导出.in文件
    function export_renting(){
        $filepath='./export/';
        $filename='renting_'.time().'.in';
        $OrderBook=M('View_order_has_book');
        $dob=$OrderBook->where(['type'=>'1','is_backed'=>'0'])->group('book_id')->field('book_id,spbs,sum(quantity) as sum_quantity,sum(num_backed) as sum_backed,sum(num_broken) as sum_broken')->select();
        $content='';
        $i=1;
        foreach($dob as $k=>$v){
            $num_renting=number_format($v['sum_quantity']-$v['sum_backed']-$v['sum_broken'],2);
            $num_renting=sprintf('%12s', $num_renting);
            $dob[$k]['num_renting']=$num_renting;

            if($i>1){
                $content.="\r\n";
            }
            $content.=$v['spbs'].'######888'.$num_renting;
            $i++;
        }
        $this->di->get('GeneralService')->writeFile($filepath.$filename,$content);
        $this->di->get('GeneralService')->outBrowser($filepath.$filename , $filename);
    }
    //导出在借数-Excel
    function export_rentingExcel(){
        $OrderBook=M('View_order_has_book');
        $dob=$OrderBook->where(['type'=>'1','is_backed'=>'0'])->group('book_id')->field('book_id,spbs,sum(quantity) as sum_quantity,sum(num_backed) as sum_backed,sum(num_broken) as sum_broken')->select();
        $i=1;
        $export=[];
        $field=['spbs','ds'];
        array_push($export,$field);
        foreach($dob as $k=>$v){
            $num_renting=number_format($v['sum_quantity']-$v['sum_backed']-$v['sum_broken'],2);
            $t=[];
            $t=[$v['spbs'],$num_renting];
            array_push($export,$t);
            $i++;
        }
        $file=$this->di->get('ExcelService')->export($export,false);
        $this->di->get('GeneralService')->outBrowser($file , 'output.xls');
    }
}